package me.pinion.plugin;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.IDataSourceProvider;
import com.jfinal.plugin.activerecord.Model;
import me.pinion.Log;
import me.pinion.kit.ClassCatch;
import me.pinion.kit.ClassKit;
import me.pinion.model.annotation.TableBind;

public class AutoActiveRecordPlugin extends ActiveRecordPlugin{

    public AutoActiveRecordPlugin(IDataSourceProvider dataSourceProvider) {
        super(dataSourceProvider);
    }

    @Override
    public boolean start() {
        ClassKit.loopClasses(new ClassCatch() {
            @Override
            public void doCatch(Class<?> clazz) {
                if (Model.class.isAssignableFrom(clazz)) {
                    TableBind bind = clazz.getAnnotation(TableBind.class);
                    if (bind != null) {
                        addMapping(bind.table(), bind.pk(), (Class<? extends Model<?>>) clazz);
                        Log.i("TableBind -> table: ", bind.table(), ", pk: ", bind.pk(), ", class: " + clazz);
                    }
                }
            }
        });
        return super.start();
    }
}
